package 面试经典150题.栈;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author tmh
 * @date 2024/6/15 16:09
 * @description
 */
public class T150逆波兰表达式求值 {
    public int evalRPN(String[] tokens) {
        Deque<String> deque = new LinkedList<>();
        for (String token : tokens) {
            if ("+".equals(token)) {
                Integer num1 = Integer.valueOf(deque.pop());
                Integer num2 = Integer.valueOf(deque.pop());
                deque.push(String.valueOf((num2 + num1)));
            } else if ("-".equals(token)) {
                Integer num1 = Integer.valueOf(deque.pop());
                Integer num2 = Integer.valueOf(deque.pop());
                deque.push(String.valueOf((num2 - num1)));
            } else if ("*".equals(token)) {
                Integer num1 = Integer.valueOf(deque.pop());
                Integer num2 = Integer.valueOf(deque.pop());
                deque.push(String.valueOf((num2 * num1)));
            } else if ("/".equals(token)) {
                Integer num1 = Integer.valueOf(deque.pop());
                Integer num2 = Integer.valueOf(deque.pop());
                deque.push(String.valueOf((num2 / num1)));
            }else {
                deque.push(token);
            }
        }
        return Integer.valueOf(deque.peek());
    }
}
